package com.education.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.education.realtime.app.BaseAppV2;
import com.education.realtime.bean.TrafficPageViewBean;

import com.education.realtime.common.Constant;
import com.education.realtime.util.AtguiguUtil;
import com.education.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Map;

import static com.education.realtime.common.Constant.*;


public class DwsTrafficVcChArIsNewPageViewWindow extends BaseAppV2 {

    public static void main(String[] args) {
        new DwsTrafficVcChArIsNewPageViewWindow().init(4002, "DwsTrafficVcChArIsNewPageViewWindow",
                                                              TOPIC_DWD_TRAFFIC_PAGE,
                                                              Constant.TOPIC_DWD_TRAFFIC_UV_DETAIL,
                                                              Constant.TOPIC_DWD_TRAFFIC_UJ_DETAIL
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          Map<String, DataStreamSource<String>> topicAndStreamMap) {
        
        // 1. 多个流union成一个流
        DataStream<TrafficPageViewBean> trafficPageViewBeanStream = unionToOne(topicAndStreamMap);
        // 2. 分组开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAggregate(trafficPageViewBeanStream);
        //        resultStream.print();
        //        resultStream.getSideOutput(new OutputTag<TrafficPageViewBean>("late") {}).print("late");
        // 3. 结果写入到clickhouse中
        writeToClickHouse(resultStream);
        
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(CLICKHOUSE_DB,
                                                             "dws_traffic_vc_ch_ar_is_new_page_view_window",
                                                             TrafficPageViewBean.class
        ));
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAggregate(DataStream<TrafficPageViewBean> stream) {
        /*
        开窗: 用什么时间? 事件时间
          滚动窗口
          
          reduce
         */
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(bean -> bean.getVc() + "_" + bean.getCh() + "_" + bean.getAr() + "_" + bean.getIsNew())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .sideOutputLateData(new OutputTag<TrafficPageViewBean>("late") {})
            .reduce(
                new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean b1,
                                                      TrafficPageViewBean b2) throws Exception {
                        b1.setUvCt(b1.getUvCt() + b2.getUvCt());
                        b1.setSvCt(b1.getSvCt() + b2.getSvCt());
                        b1.setPvCt(b1.getPvCt() + b2.getPvCt());
                        b1.setDurSum(b1.getDurSum() + b2.getDurSum());
                        b1.setUjCt(b1.getUjCt() + b2.getUjCt());
                        
                        return b1;
                    }
                },
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TrafficPageViewBean> elements,
                                        Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean bean = elements.iterator().next();
                        String stt = AtguiguUtil.toDate(ctx.window().getStart());
                        String edt = AtguiguUtil.toDate(ctx.window().getEnd());
                        
                        bean.setStt(stt);
                        bean.setEdt(edt);
                        
                        bean.setTs(System.currentTimeMillis());  //把ts设置为系统时间, 表示这个结果的统计时间
                        
                        out.collect(bean);
                        
                    }
                }
            );
        
    }
    
    private DataStream<TrafficPageViewBean> unionToOne(Map<String, DataStreamSource<String>> topicAndStreamMap) {
        SingleOutputStreamOperator<TrafficPageViewBean> pvSvDuringTimeStream = topicAndStreamMap
            .get(TOPIC_DWD_TRAFFIC_PAGE)
            .map(new MapFunction<String, TrafficPageViewBean>() {
                @Override
                public TrafficPageViewBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    Long ts = obj.getLong("ts");
                    
                    Long uvCt = 0L;
                    Long svCt = page.getString("last_page_id") == null ? 1L : 0L;
                    Long pvCt = 1L;
                    Long durSum = page.getLong("during_time");
                    Long ujCt = 0L;
                    
                    
                    return new TrafficPageViewBean("", "",
                                                   vc, ch, ar, isNew,
                                                   uvCt, svCt, pvCt, durSum, ujCt,
                                                   ts
                    );
                    
                }
            });
        
        SingleOutputStreamOperator<TrafficPageViewBean> uvStream = topicAndStreamMap
            .get(TOPIC_DWD_TRAFFIC_UV_DETAIL)
            .map(json -> {
                
                JSONObject obj = JSON.parseObject(json);
                JSONObject common = obj.getJSONObject("common");
                JSONObject page = obj.getJSONObject("page");
                
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String isNew = common.getString("is_new");
                Long ts = obj.getLong("ts");
                
                Long uvCt = 1L;
                Long svCt = 0L;
                Long pvCt = 0L;
                Long durSum = 0L;
                Long ujCt = 0L;
                
                
                return new TrafficPageViewBean("", "",
                                               vc, ch, ar, isNew,
                                               uvCt, svCt, pvCt, durSum, ujCt,
                                               ts
                );
                
                
            });
        
        
        SingleOutputStreamOperator<TrafficPageViewBean> ujStream = topicAndStreamMap
            .get(TOPIC_DWD_TRAFFIC_UJ_DETAIL)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                JSONObject common = obj.getJSONObject("common");
                JSONObject page = obj.getJSONObject("page");
                
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String isNew = common.getString("is_new");
                Long ts = obj.getLong("ts");
                
                Long uvCt = 0L;
                Long svCt = 0L;
                Long pvCt = 0L;
                Long durSum = 0L;
                Long ujCt = 1L;
                
                
                return new TrafficPageViewBean("", "",
                                               vc, ch, ar, isNew,
                                               uvCt, svCt, pvCt, durSum, ujCt,
                                               ts
                );
                
            });
        
        return pvSvDuringTimeStream.union(ujStream, uvStream);
    }
}
